<template>
  <view class="u-navbar">
    <view class="u-navbar-fixed">
      <view class="u-status-bar"></view>
      <view class="u-navbar-inner">
        <view class="header">
          <view class="header_content">
            <view class="header_box">
              <view class="header_section">
                <view class="header_img" @click="back()">
                  <image
                    style="width: 84rpx"
                    src="https://hengxiao-resource.oss-cn-hangzhou.aliyuncs.com/web/resources/images/hengxiao/header/back.png"
                    mode="widthFix"
                  />
                </view>
                <view class="header_img" @click="print()" v-if="printFlag">
                  <image
                    style="width: 72rpx"
                    src="https://hengxiao-resource.oss-cn-hangzhou.aliyuncs.com/web/resources/images/hengxiao/header/print.png"
                    mode="widthFix"
                  />
                </view>
                <view class="header_img" @click="goHome()">
                  <image
                    style="width: 56rpx"
                    src="https://hengxiao-resource.oss-cn-hangzhou.aliyuncs.com/web/resources/images/hengxiao/header/home.png"
                    mode="widthFix"
                  />
                </view>
                <view class="header_tips" v-if="tipsFlag">
                  <text>【认识的单词打</text>
                  <image
                    src="https://hengxiao-resource.oss-cn-hangzhou.aliyuncs.com/web/resources/images/hengxiao/word/icon_dui_active.png"
                    mode="scaleToFill"
                  />
                  <text>，不认识的单词打</text>
                  <image
                    src="https://hengxiao-resource.oss-cn-hangzhou.aliyuncs.com/web/resources/images/hengxiao/word/icon_cuo_active.png"
                    mode="scaleToFill"
                  />
                  <text> ；</text>
                  <image
                    src="https://hengxiao-resource.oss-cn-hangzhou.aliyuncs.com/web/resources/images/hengxiao/word/icon_dui_active.png"
                    mode="scaleToFill"
                  />
                  <text> 单词直接进入测试，</text>
                  <image
                    src="https://hengxiao-resource.oss-cn-hangzhou.aliyuncs.com/web/resources/images/hengxiao/word/icon_cuo_active.png"
                    mode="scaleToFill"
                  />
                  <text> 单词进行练习】</text>
                </view>
              </view>
              <view class="header_section" v-if="userInfoFlag">
                <view class="avatar">
                  <view class="avatar_content">
                    <image :src="userInfo.headImg" mode="scaleToFill" />
                  </view>
                  <view class="avatar_icon"> </view>
                </view>
                <view class="info">
                  <view class="username"> {{ userInfo.userName }} </view>
                  <view class="address">
                    <image
                      src="https://hengxiao-resource.oss-cn-hangzhou.aliyuncs.com/web/resources/images/hengxiao/common/address.png"
                      mode="scaleToFill"
                    />
                    <text>{{ userInfo.cityName }}</text>
                  </view>
                </view>
              </view>
              <view class="header_section" v-if="selectTextbookFlag">
                <view class="textbook" @click="selectTextbook()">
                  <view class="textbook_icon"> </view>
                  <view class="textbook_text"> 选择教材 </view>
                </view>
              </view>
            </view>
            <view class="header_center">
              <view class="title" v-if="titleFlag">
                {{ title }}
              </view>
            </view>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
const modal = uni.requireNativePlugin("modal");
import api from "@/libs/lpapi-uniplugin";
import { getStore } from "@/libs/storage";
export default {
  components: {},
  props: {
    title: {
      type: String,
      default: "",
    },
    titleFlag: {
      type: Boolean,
      default: true,
    },
    userInfoFlag: {
      type: Boolean,
      default: true,
    },
    selectTextbookFlag: {
      type: Boolean,
      default: false,
    },
    tipsFlag: {
      type: Boolean,
      default: false,
    },
    printFlag: {
      type: Boolean,
      default: false,
    },
    printData: {
      type: Array,
      default: () => [],
    },
  },
  data() {
    return {
      userInfo: {},
      searchVal: "",
      printerList: [],
      printerMap: new Map(),
      index: 0,
      gapList: [
        {
          name: "随打印机设置",
          value: -1,
        },
        {
          name: "连续纸",
          value: 0,
        },
        {
          name: "定位孔",
          value: 1,
        },
        {
          name: "间隙纸",
          value: 2,
        },
      ],
      gapIndex: 0,
      printModes: [
        {
          name: "打印",
          value: 0,
        },
        {
          name: "预览",
          value: 1,
        },
      ],
      printMode: 0,
      gapIndex: 0,
      previewList: [],
    };
  },
  created() {
    this.userInfo = getStore({
      name: "userInfo",
    });
  },
  methods: {
    goHome() {
      uni.reLaunch({
        url: "/pages/index/index",
      });
    },
    back() {
      uni.navigateBack({
        delta: 1,
      });
    },
    selectTextbook() {
      this.$emit("select");
    },
    print() {
      this.startDiscovery();
    },
    startDiscovery() {
      api.getPrinterName().then((res) => {
        if (res.data === "DPXX-XXXXXXXX") {
          // 1. 搜索前先清空设备列表
          this.printerList.splice(0);
          this.printerMap.clear();
          this.index = 0;
          // 2. 显示加载状态；
          uni.showLoading({
            title: "正在搜索打印机，请稍后。。。",
          });
          // 2. 开始搜索蓝牙设备
          api.startDiscovery({
            timeout: 5000,
            interval: 200,
            onDeviceFound: (devices) => {
              // 检测到蓝牙设备
              for (let item of devices) {
                this.onDeviceFound(item);
              }
              this.openPrinter();
            },
            complete: (res) => {
              // 蓝牙设备搜索完毕；
              uni.hideLoading();
              // clearInterval(timer);
              if (res && res.statusCode > 1) {
                if (this.printerList.length <= 0) {
                  this.printerList.push("未检测到打印机");
                  uni.showToast({
                    title: "未检测到打印机！",
                    icon: "none",
                    duration: 2000,
                  });
                } else {
                  // this.openPrinter();
                }
              }
            },
          });
        } else {
          this.printTable();
        }
      });
    },
    stopDiscovery() {
      api.stopDiscovery();
    },
    onDeviceFound(device) {
      if (!device) return;
      //
      if (!this.printerMap.has(device.deviceId)) {
        this.printerList.push(device.name);
      }
      //
      this.printerMap.set(device.deviceId, device);
    },
    async openPrinter() {
      const printerName = this.getPrinterName();
      if (printerName) {
        // 连接新的打印机
        api.openPrinter(printerName, (value) => {
          if (value) {
            modal.toast({
              message: "打印机连接成功",
              duration: 1.5,
            });
            this.printTable();
          }
        });
      }
    },
    closePrinter() {
      api.closePrinter();
    },
    getPrinterName() {
      return this.printerList[this.index];
    },
    getJobName() {
      if (this.printMode === 1) {
        return "#!#preview#!#";
      } else {
        return "";
      }
    },
    getPrintParam() {
      const data = {};
      const gapValue = this.gapList[this.gapIndex];
      if (gapValue >= api.printParamValue.gapType.none) {
        // data[api.printParamName.gapType] = this.gapList[this.gapIndex].value;
        data["GAP_TYPE"] = this.gapList[this.gapIndex].value;
      }
      return data;
    },
    previewJob(info) {
      this.previewList.splice(0);
      if (info.pages) {
        for (let item of info.pages) {
          // uniapp中如果base64字符串中有 '\n'或者'\r'，无法正常展示
          item = item.replace(/[\r\n]/g, "");
          this.previewList.push({
            key: Math.random(),
            value: item,
          });
        }
      }
    },
    async printTable() {
      const labelWidth = 75;
      const labelHeight = this.printData.length * 10;
      const rows = this.printData.length;
      const cols = 2;
      // 上下左右各留2.5毫米的边距，可避免标签纸松动造成打印到标签纸外边的问题；
      const margin = 2.5;
      // 表格的宽度（减去左右留白）
      const tableWidth = labelWidth - margin * 2;
      // 表格的高度（减去上下留白）
      const tableHeight = labelHeight - margin * 2;
      // 表格单元格宽度
      const cellWidth = tableWidth / cols;
      // 表格单元格高度
      const cellHeight = tableHeight / rows;
      // 表格线条宽度
      const lineWidth = 0.4;
      //
      let posX = margin;
      let posY = margin;
      if (await this.checkAndOpenPrinter()) {
        // 创建指定大小的打印任务
        await api.startJob({
          width: labelWidth,
          height: labelHeight,
          jobName: this.getJobName(),
        });
        // 绘制外边框
        await api.drawRectangle({
          x: margin,
          y: margin,
          width: tableWidth,
          height: tableHeight,
          lineWidth: lineWidth,
        });
        for (let i = 0; i < rows - 1; i++) {
          // 循环绘制横线
          posY += cellHeight;
          await api.drawLine({
            x1: margin,
            y1: posY,
            x2: margin + tableWidth,
            y2: posY,
            lineWidth: lineWidth,
          });
        }
        // 绘制第一条竖线，虚线
        posX += cellWidth;
        await api.drawDashLine({
          x1: posX,
          y1: margin,
          x2: posX,
          y2: margin + tableHeight,
          dashLen: [1, 1], // 0.5毫米实线，0.5毫米空白
          lineWidth: lineWidth,
        });
        // 循环绘制表格内容
        for (let row = 0; row < rows; row++) {
          for (let col = 0; col < cols; col++) {
            const cellX = margin + col * cellWidth;
            const cellY = margin + row * cellHeight;
            const text =
              (col === 0
                ? this.printData[row].word
                : this.printData[row].wordParaphrase) || ""; // 获取单元格内容

            // 在单元格中绘制文本
            await api.drawText({
              text: text,
              x: cellX + 1, // 留出一些边距
              y: cellY + 1,
              width: cellWidth - 2, // 留出一些边距
              height: cellHeight - 2,
              fontStyle: 0, // 常规样式
              horizontalAlignment: 1, // 水平居中对齐
              verticalAlignment: 1, // 垂直居中对齐
            });
          }
        }
        // 提交打印任务
        // await api.commitJob();
        const printParam = this.getPrintParam();
        const result = await api.commitJob(printParam);
        this.previewJob(result);
      }
    },
    checkAndOpenPrinter() {
      return new Promise((resolve) => {
        const printerName = this.getPrinterName();
        api
          .openPrinter({
            name: printerName,
          })
          .then((result) => {
            resolve(result);
          });
      });
    },
  },
};
</script>

<style lang="scss" scoped>
@import "./Header.scss";
</style>
